package com.doctorliang.cheng.shopping.type.fragment;

import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.Toast;

import com.doctorliang.cheng.shopping.R;
import com.doctorliang.cheng.shopping.base.BaseFragment;
import com.doctorliang.cheng.shopping.type.adapter.TagGridViewAdapter;
import com.doctorliang.cheng.shopping.type.bean.TagBean;
import com.doctorliang.cheng.shopping.utils.Constants;
import com.doctorliang.cheng.shopping.utils.ToastUtil;
import com.google.gson.Gson;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.List;

import okhttp3.Call;
import okhttp3.Request;

/**
 * 标签页面
 * Created by YBH on 2017/12/14.
 */

public class TagFragment extends BaseFragment {
    private GridView gv_tag;
    private List<TagBean.ResultBean> result;
    private TagGridViewAdapter adapter;

    @Override
    public View initView() {
        View view = View.inflate(mcontext, R.layout.fragment_tag, null);
        gv_tag = (GridView) view.findViewById(R.id.gv_tag);
        return view;
    }

    @Override
    public void initData() {
        super.initData();
        getDataFromNet();
        initListener();
    }

    private void initListener() {
        gv_tag.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                ToastUtil.show(mcontext,""+result.get(position).getName(),Toast.LENGTH_SHORT);
            }
        });
    }

    private void getDataFromNet() {
        OkHttpUtils.get().url(Constants.TAG_URL).id(100).build().execute(new MyStringCallback());

    }

    private class MyStringCallback extends StringCallback {

        @Override
        public void onBefore(Request request, int id) {
        }

        @Override
        public void onAfter(int id) {
        }

        @Override
        public void onError(Call call, Exception e, int id) {

        }

        @Override
        public void onResponse(String response, int id) {
            switch (id) {
                case 100:
//                    Toast.makeText(mContext, "http", Toast.LENGTH_SHORT).show();
                    if (response != null) {
                        processData(response);
                        adapter = new TagGridViewAdapter(mcontext, result);
                        gv_tag.setAdapter(adapter);
                    }
                    break;
                case 101:
                    Toast.makeText(mcontext, "https", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    }

    private void processData(String json) {
        Gson gson = new Gson();
        TagBean tagBean = gson.fromJson(json, TagBean.class);
        result = tagBean.getResult();
    }
}
